#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
void* func1(void*);
void* func2(void*);
typedef struct
{
	int deposit;
	sem_t sem;
}Account;
int main(void)
{
	pthread_t thread1_id,thread2_id;
	Account account = {888};
	sem_init(&account.sem,0,1);
	pthread_create(&thread1_id,NULL,func1,(void*)&account);
	pthread_create(&thread2_id,NULL,func2,(void*)&account);
	pthread_join(thread1_id,NULL);
	pthread_join(thread2_id,NULL);
	return 0;
}
void* func1(void* data)
{
	Account* a = (Account*)data;
	// P(1)
	sem_wait(&a->sem);
	if(a->deposit >= 888)
	{
		a->deposit -= 888;
	}
	// V(1)
	sleep(2);
	printf("func1; deposit = %d\n",a->deposit);
	sem_post(&a->sem);
	return (void*)NULL;
}
void* func2(void* data)
{
	Account* a = (Account*)data;
	// P(1)
	sem_wait(&a->sem);
	if(a->deposit >= 888)
	{
		a->deposit -= 888;
	}
	// V(1)
	sleep(1);
	printf("func2; deposit = %d\n",a->deposit);
	sem_post(&a->sem);
	return (void*)NULL;
}

